﻿#include "LogicController.h"

LogicController::LogicController(QObject *parent) :
    QObject(parent)
{
    automaticTimer = new QTimer(this);
    automaticTimer->setInterval(500);
    connect(automaticTimer, SIGNAL(timeout()), this, SLOT(automaticSlot()));
    automaticTimer->start();

    CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();
    Q_UNUSED(currentPointStore);



    registerFuncHandler(ControlKNXFunc::FunctionCode, &LogicController::controlKNXFuncHandle);
    registerFuncHandler(ControlPointFunc::FunctionCode, &LogicController::controlPointFuncHandle);
    registerFuncHandler(LogicCloudDataFunc::FunctionCode, &LogicController::LogicCloudDataFuncHandle);
    registerFuncHandler(DownloadFileFunc::FunctionCode, &LogicController::downloadFileFuncHandle);
}

void LogicController::registerDevice(BaseDevice *device)
{
    QString deviceName = device->name();
    m_deviceList.insert(deviceName,device);
    qDebug()<<"logicController registerDevice succe";
    connect(device,SIGNAL(transferFuncSignal(QSharedPointer<BaseFunc>)),this,SLOT(transferFuncSlot(QSharedPointer<BaseFunc>)));
    connect(this,SIGNAL(transferFuncSignal(QSharedPointer<BaseFunc>)),device,SLOT(transferFuncSlot(QSharedPointer<BaseFunc>)));    
}

void LogicController::transferFuncSlot(QSharedPointer<BaseFunc> sharedFunc)
{
    funcHandle(sharedFunc);
}

void LogicController::registerFuncHandler(int functionCode, LogicController::HandlePointer pHandle)
{
    qDebug()<<"instert functionCode="<<functionCode;
    m_handleMap.insert(functionCode,pHandle);
}

void LogicController::funcHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    int functionCode = sharedFunc->functionCode();
    qDebug()<<"LOfunction="<<functionCode;
    HandlePointer pHandle = m_handleMap.value(functionCode,NULL);
    if(pHandle != NULL)
    {
        (this->*pHandle)(sharedFunc);
    }
}

void LogicController::controlKNXFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
     qDebug()<<"################# LogicController::controlKNXFuncHandle";
     ControlKNXFunc *knxControlFunc = qobject_cast<ControlKNXFunc*>(sharedFunc.data());
     QList<SWKNXDataStruct> controlKNXList;

     QList<ControlPointStruct> controlPointList;

     SWKNXListXml *swKNXListXml = SWKNXListXml::getInstance();

     QList<SWKNXDataStruct> sourceKNXList = knxControlFunc->sourceKNXList();

     QList<SWKNXDataStruct> xmlKNXList = swKNXListXml->knxDataList();

    qDebug()<<"[LogicController::controlKNXFuncHandle] sourceKNXList.size = "<<sourceKNXList.size();
     if(sourceKNXList.size() > 0)
     {
          qDebug()<<"[LogicController::controlKNXFuncHandle] sourceKNXList.size = "<<sourceKNXList.at(0).groupAddress()<<","<<sourceKNXList.at(0).knxLen();
          qDebug()<<"[LogicController::controlKNXFuncHandle] sourceKNXList.size = "<<DataTypeConver::formatString(sourceKNXList.at(0).dataList());

     }
     controlPointList.append(swKNXListXml->controlPointList(sourceKNXList));

     qDebug()<<"[ogicController::controlKNXFuncHandle] controlPointList.size = "<<controlPointList.size();
     if(controlPointList.size() > 0)
     qDebug()<<"[ogicController::controlKNXFuncHandle] controlPointList.size = "<<controlPointList.at(0).address()<<","<<controlPointList.at(0).value();

     QList<ControlPointStruct> removeDuplicatesControlPointList = controlPointList.toSet().toList();



     knxControlFunc->setControlPointList(removeDuplicatesControlPointList);

     UpdatePointFunc  *updatePointFunc  = new UpdatePointFunc();
     QList<ControlPointStruct> updatePointList;
     updatePointList.append(removeDuplicatesControlPointList);
     updatePointFunc->setUpdatePointList(updatePointList);
     printf("updatePointList size is %d\r\n",updatePointList.size());
     //printf("updatePointList add value is %d  %d\r\n",updatePointList.at(0).address(),updatePointList.at(0).value());
     //printf("updatePointList add value is %d  %d\r\n",updatePointList.at(1).address(),updatePointList.at(1).value());
     QSharedPointer<BaseFunc> shareUpdatePointFunc(updatePointFunc);


     emit transferFuncSignal(shareUpdatePointFunc);

     ControlPointFunc  *controlPointFunc  = new ControlPointFunc();
     QList<ControlPointStruct> _controlPointList;
     _controlPointList.append(removeDuplicatesControlPointList);
     controlPointFunc->setSourceDevice("SWKNXDevice");
     controlPointFunc->setControlPointList(_controlPointList);

     QSharedPointer<BaseFunc> shareControlPointFunc(controlPointFunc);


     emit transferFuncSignal(shareControlPointFunc);
     /*for(int i=0;i<xmlKNXList.size();i++)
     {
         if(sourceKNXList[0].groupAddress() == xmlKNXList[i].groupAddress())
         {
             qDebug()<<"haha  groupAddress-"<<sourceKNXList[0].groupAddress();
         }
         if(sourceKNXList[0].dataList() == xmlKNXList[i].dataList())
         {
              qDebug()<<"haha  dataList-"<<DataTypeConver::formatString(sourceKNXList[0].dataList());
         }
     }*/


}

void LogicController::controlPointFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    qDebug()<<"[LogicController::controlPointFuncHandle]-LogicController NOW";
    ControlPointFunc *pointControlFunc = qobject_cast<ControlPointFunc*>(sharedFunc.data());
    QList<ControlPointStruct> controlPointList;

    SceneListXml *sceneListXml = SceneListXml::getInstance();
    RangeListXml *rangeListXml = RangeListXml::getInstance();
    LogicControlXml *logicControlXml = LogicControlXml::getInstance();
    CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();

    QList<ControlPointStruct> sourcePointList = pointControlFunc->sourcePointList();
    printf("[LogicController::controlPointFuncHandle]-sourcePointList size is %d\r\n",sourcePointList.size());
    printf("[LogicController::controlPointFuncHandle]-sourcePointList add value is %d  %d\r\n",sourcePointList.at(0).address(),sourcePointList.at(0).value());
   // printf("controlPointList size is %d\r\n",controlPointList.size());

        currentPointStore->insert(sourcePointList);
        {
            automaticTimer->stop();
            lastTime="00:00:00";
            automaticSlot();
            automaticTimer->start();
        }
    controlPointList.append(sceneListXml->controlPointList(sourcePointList));
    printf("[LogicController::controlPointFuncHandle]-111controlPointList size is %d\r\n",controlPointList.size());
    if(controlPointList.size() > 0)
    printf("[LogicController::controlPointFuncHandle]-controlPointList add value is %d  %d\r\n",controlPointList.at(0).address(),controlPointList.at(0).value());
    controlPointList.append(rangeListXml->controlPointList(sourcePointList));

    QList<ControlPointStruct> logicPointList;
    logicPointList.append(logicControlXml->controlPointList(sourcePointList));
    logicPointList.append(logicControlXml->controlPointList(controlPointList));
    controlPointList.append(logicPointList);

    QList<ControlPointStruct> removeDuplicatesControlPointList = controlPointList.toSet().toList();

  //  currentPointStore->insert(sourcePointList);
    currentPointStore->insert(removeDuplicatesControlPointList);

    pointControlFunc->setControlPointList(removeDuplicatesControlPointList);

    UpdatePointFunc  *updatePointFunc  = new UpdatePointFunc();
    QList<ControlPointStruct> updatePointList;
    updatePointList.append(sourcePointList);
    updatePointList.append(removeDuplicatesControlPointList);
    updatePointFunc->setUpdatePointList(updatePointList);
   // printf("removeDuplicatesControlPointList size is %d\r\n",removeDuplicatesControlPointList.size());
    printf("updatePointList size is %d\r\n",updatePointList.size());
    //printf("updatePointList add value is %d  %d\r\n",updatePointList.at(0).address(),updatePointList.at(0).value());
    //printf("updatePointList add value is %d  %d\r\n",updatePointList.at(1).address(),updatePointList.at(1).value());
    QSharedPointer<BaseFunc> shareUpdatePointFunc(updatePointFunc);



     QList<SWKNXDataStruct> controlKNXList;
    ControlKNXFunc *knxControlFunc = new ControlKNXFunc();
    controlKNXList.append(sceneListXml->controlKNXList(sourcePointList));
    knxControlFunc->setSourceKNXList(controlKNXList);
    QSharedPointer<BaseFunc> shareControlKNXFunc(knxControlFunc);


    emit transferFuncSignal(shareUpdatePointFunc);
    emit transferFuncSignal(sharedFunc);
    emit transferFuncSignal(shareControlKNXFunc);

}

void LogicController::downloadFileFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    DownloadFileFunc *downloadFileFunc = qobject_cast<DownloadFileFunc*>(sharedFunc.data());
    PortStruct source = downloadFileFunc->source();
    quint8 fileType = downloadFileFunc->fileType();
    QString url = downloadFileFunc->url();
    QMap<QString,QString> paramMap = downloadFileFunc->paramMap();
    QByteArray sha = QByteArray::fromHex(paramMap.value("sha1").toLatin1());
    System *system = System::getInstance();
    QString path = system->rootPath() + "/Download";

    Download *download = new Download(this);
    connect(download,SIGNAL(downloadFinishedSignal(PortStruct,bool,quint8,QString)),this,SLOT(downloadFinisedSlot(PortStruct,bool,quint8,QString)));
    download->setParam(source,fileType,url,sha,path);
    download->start();
}


void LogicController::automaticSlot()
{
   // static QString lastTime;
    static quint16 runTime[16]={0};
    QDateTime systemTime(QDateTime::currentDateTime());
    QString strTime = systemTime.toString("hh:mm:ss");
    // qDebug()<<"hello";
    if(lastTime == strTime)
    {
        return;
    }
    lastTime = strTime;

    AutomaticXml *automaticXml = AutomaticXml::getInstance();
    ModbusListXml *modbusListXml = ModbusListXml::getInstance();
    CurrentPointStore *currentPointStore = CurrentPointStore::getInstance();
    SavePointXml *savePointXml =SavePointXml::getInstance();
    QList<AutomaticStruct> automaticList;
    QList<ControlPointStruct> currntPointList = currentPointStore->currentPointList();
    /*modubs Query data*/
    for(quint16 queryNo=0;queryNo<modbusListXml->m_queryNum;queryNo++)
    {
        ModbusControlStruct dataStruct;
        ModbusProtocol modbusprotocol;
        dataStruct=modbusListXml->m_modbusQueryMap.value(queryNo);

        if(runTime[queryNo]<dataStruct.queryTime())
        {
            runTime[queryNo]++;
         //   qDebug()<<runTime[queryNo];
        }else if(modbusListXml->m_queryStata==0)
        {
          modbusListXml->m_queryStata=0;
          runTime[queryNo]=0;
          modbusListXml->m_queryNo=queryNo;
          QByteArray data = modbusprotocol.getmodbusData(dataStruct.deviceAddress(),dataStruct.functionCode(),dataStruct.registerStartAddress());

          SendQueryData  *sendQueryData  = new SendQueryData();
          sendQueryData->setData(data);
          QSharedPointer<BaseFunc> SendQuery(sendQueryData);         
         emit transferFuncSignal(SendQuery);

        }
    }

    for(int i=0; i<automaticXml->automaticList().size(); i++)
    {
        AutomaticStruct automatic = automaticXml->automaticList().at(i);
        if(!automatic.isExecute())
        {
            automaticList.append(automatic);
         //       break;
                continue;
        }

        quint16 satisfyCount = 0;
        quint16 satisfySize = 0;

        QList<TimeConditionStruct> timeConditionList;
        if(automatic.conditionSatisfyType() == AutomaticStruct::AllSatisfy)
        {
            if(automatic.timeConditionList().size()>0)
            {
               satisfySize=satisfySize+1;
            }
        }
        else
        {
        satisfySize += automatic.timeConditionList().size();
        }
        for(int j=0; j<automatic.timeConditionList().size(); j++)
        {
            QLocale locale = QLocale::English;
            QString dateTime = locale.toString(systemTime,"yyyy-MM-dd hh:mm:ss");
            QString weekTime = locale.toString(systemTime,"dddd hh:mm:ss");

            TimeConditionStruct timeCondition = automatic.timeConditionList().at(j);
            if((timeCondition.time() == dateTime) || (timeCondition.time() == weekTime))
            {
                satisfyCount++;
                timeCondition.setIsSatisfy(true);
            }
            else
            {
               timeCondition.setIsSatisfy(false);
            }
            timeConditionList.append(timeCondition);
        }
        automatic.setTimeConditionList(timeConditionList);

        QList<EquipmentConditionStruct> equipmentConditionList;
        satisfySize += automatic.equipmentConditionList().size();
        for(int j=0; j<automatic.equipmentConditionList().size(); j++)
        {
            EquipmentConditionStruct equipmentCondition = automatic.equipmentConditionList().at(j);
            foreach (const ControlPointStruct &currentPoint, currntPointList)
            {
            //   qDebug()<<"currentPointADDr="<<currentPoint.address();
           //    qDebug()<<"currentPointvalue="<<currentPoint.value();
           //    qDebug()<<"equipment="<<equipmentCondition.address();
           //     qDebug()<<"equipmentvalue="<<equipmentCondition.functionValue();
                if(equipmentCondition.conditionType() == EquipmentConditionStruct::IsThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() == equipmentCondition.functionValue()))
                    {
                           qDebug()<<"currentPointADDr="<<currentPoint.address();
                           qDebug()<<"equipment="<<equipmentCondition.address();
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }
                else if(equipmentCondition.conditionType() == EquipmentConditionStruct::NotThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() != equipmentCondition.functionValue()))
                    {
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }
                else if(equipmentCondition.conditionType() == EquipmentConditionStruct::LessThanThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() < equipmentCondition.functionValue()))
                    {
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }
                else if(equipmentCondition.conditionType() == EquipmentConditionStruct::LessThanOrEqualToThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() <= equipmentCondition.functionValue()))
                    {
                        qDebug()<<"right satisfyCount++";
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }
                else if(equipmentCondition.conditionType() == EquipmentConditionStruct::MoreThanThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() > equipmentCondition.functionValue()))
                    {
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }

                else if(equipmentCondition.conditionType() == EquipmentConditionStruct::MoreThanOrEqualToThisValue)
                {
                    if((currentPoint.address() == equipmentCondition.address()) && (currentPoint.value() >= equipmentCondition.functionValue()))
                    {
                        satisfyCount++;
                        equipmentCondition.setIsSatisfy(true);
                    }
                    else
                    {
                        equipmentCondition.setIsSatisfy(false);
                    }
                }
            }
            equipmentConditionList.append(equipmentCondition);
        }
        automatic.setEquipmentConditionList(equipmentConditionList);

        if((automatic.conditionSatisfyType() == AutomaticStruct::AnyOneSatisfy) && (satisfyCount > 0))
        {
            automatic.setIsSatisfy(true);
//            qDebug()<<"satisfycount="<<satisfyCount;
        }
        else if((automatic.conditionSatisfyType() == AutomaticStruct::AllSatisfy) && (satisfyCount == satisfySize)&&(satisfyCount>0))
        {
            automatic.setIsSatisfy(true);
        }
        else
        {
            automatic.setIsSatisfy(false);
        }

        if((automatic.isSatisfy()) && (automatic.isSatisfy() != automatic.isHasSatisfy()))
        {
            qDebug()<<"Excute Action!!!";
            QList<ActionStruct> actionList = automatic.actionList();
            QList<ControlPointStruct> sourcePointList;
            QList<ControlPointStruct> controlPointList;
            foreach (const ActionStruct &action, actionList)
            {
                ControlPointStruct sourcePoint;
                int address = action.address();
                int value   = action.functionValue();
                quint64 delaytime=action.delayTime()/100;
                qDebug()<<"[LogicController::automaticSlot]-"<<address<<","<<value<<" "<<delaytime;
                sourcePoint.setAddress(address);
                sourcePoint.setValue(value);
                sourcePoint.setDelayTime(delaytime);
                sourcePointList.append(sourcePoint);

                QString text;
                QString addrdata;QString addrvalue;
                addrdata=QString::number(address);
                addrvalue=QString::number(value);
                text="auto-timeover-"+action.zoneName()+"-"+action.deviceName()+"-"+action.functionName()+"-"+action.valueName()+"-addr="+addrdata+"-value="+addrvalue;
                TextRecord(text);


            }

            SceneListXml *sceneListXml = SceneListXml::getInstance();
            RangeListXml *rangeListXml = RangeListXml::getInstance();
            LogicControlXml *logicControlXml = LogicControlXml::getInstance();

            controlPointList.append(sourcePointList);
           // controlPointList.append(sceneListXml->controlPointList(sourcePointList));
           // controlPointList.append(rangeListXml->controlPointList(sourcePointList));

            QList<ControlPointStruct> logicPointList;
            logicPointList.append(logicControlXml->controlPointList(controlPointList));
            controlPointList.append(logicPointList);

            QList<ControlPointStruct> removeDuplicatesControlPointList = controlPointList.toSet().toList();

            currentPointStore->insert(removeDuplicatesControlPointList);

            ControlPointFunc *pointControlFunc = new ControlPointFunc;
            pointControlFunc->setControlPointList(removeDuplicatesControlPointList);
            QSharedPointer<BaseFunc> sharePointControlFunc(pointControlFunc);

            UpdatePointFunc  *updatePointFunc  = new UpdatePointFunc();
            updatePointFunc->setUpdatePointList(removeDuplicatesControlPointList);
            QSharedPointer<BaseFunc> shareUpdatePointFunc(updatePointFunc);
            currentPointStore->clearnMap();




            emit transferFuncSignal(shareUpdatePointFunc);
            emit transferFuncSignal(sharePointControlFunc);
        }

        automatic.setIsHasSatisfy(automatic.isSatisfy());
        automaticList.append(automatic);
    }
    automaticXml->setAutomaticList(automaticList);

    quint16 savePointTime=savePointXml->getsavetime();

    if(savePointTime>600)
    {
        savePointXml->clernsavetime();
        if(savePointXml->TurnStata()==true)
        {
            savePointXml->setSynchroTime(strTime);
            QMap<quint16,SavePointStruct>dataMap=savePointXml->getMap();
            QList<quint16>dataList=savePointXml->getList();
            foreach(const quint16 &addr,dataList)
            {
                SavePointStruct getStruct=dataMap.value(addr);
                savePointXml->modify(getStruct);
                savePointXml->saveTurnStata(false);
            }
            qDebug()<<"time out savepoint now";
            system("sync");
        }
        savePointXml->setSynchroTime(strTime);
 //       qDebug()<<"time over but fals";
    }
    savePointXml->timeup();


    if(automaticXml->getBestStata()==true)
    {
        quint16 bestTime=automaticXml->getBestTime();
        if(bestTime>35)
        {
            qDebug()<<"try to take IP now---------------------------------------------------------------";
            system("udhcpc -ieth0 &");
            bestTime=0;
            automaticXml->setBestTime(bestTime);
        }
        else
        {
            bestTime++;
       //     qDebug()<<"best time up now";
            automaticXml->setBestTime(bestTime);
        }

    }

    /******************/
    quint16 getTime=automaticXml->getTimetoGO();
    getTime++;
    automaticXml->setTimetoGO(getTime);
    if(automaticXml->getTimetoGO()>=600)
    {
        automaticXml->setTimetoGO(0);
        QList<SavePointStruct> dataList= savePointXml->getSystemList();
        qDebug()<<"This time to Save Systemdata";
        foreach(SavePointStruct dataStruct,dataList)
        {
            static QMutex mutex;
            mutex.lock();
            QString text;
            QString currentTime = dataStruct.getTime();
            QString addrdata= QString::number(dataStruct.pointAddr());
            QString valuedata= QString::number(dataStruct.pointValue());
            text =currentTime +"-Addr=("+addrdata+")" + "-Value=("+valuedata+")"+ "-STATA="+dataStruct.getStata()+"\r\n";
            QByteArray textArray = text.toLatin1();
            fprintf(stderr, textArray.constData());

            QFile file(QCoreApplication::applicationDirPath() + "/systemdata.txt");
            file.open(QIODevice::WriteOnly | QIODevice::Append);
            QTextStream textStream(&file);
            textStream << text;
            file.flush();
            file.close();
            if(file.size()>0x700000)
            {
                qDebug()<<"This file size is >1M,remove now";
                file.remove();
            }
            mutex.unlock();
        }
       savePointXml->clearnSystemList();

    }

//    /********rs485time******/
//    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd");
//    qDebug()<<strTime;
//    if(strTime=="03:00:00")
//    {
//        qDebug()<<"This time to send";
//        QByteArray gettimedata;
//        QString getdaydata;
//        quint16 Yeardata=currentTime.mid(0,4).toInt();
//        quint8 monthdata=c    urrentTime.mid(6,2).toInt();
//        quint8 daydata=currentTime.mid(9,2).toInt();
//        quint8 hourdata=strTime.mid(0,2).toInt();
//        quint8 minutedata=strTime.mid(3,2).toInt();
//        quint8 seconddata=strTime.mid(6,2).toInt();
//        getdaydata.append(QString::number(Yeardata,16));
//        getdaydata.append(QString::number(monthdata,16));
//        getdaydata.append(QString::number(daydata,16));
//        getdaydata.append(QString::number(hourdata,16));
//        getdaydata.append(QString::number(minutedata,16));
//        getdaydata.append(QString::number(seconddata,16));
//        QByteArray data;
//        data.append();

//        Package package;
//        package.setBody(getdaydata);
//        RS485setTime *RS485setTimefunc = new RS485setTime();
//        RS485setTimefunc->setPackage(package);
//        QSharedPointer<BaseFunc> RS485settime(RS485setTimefunc);
//        emit transferFuncSignal(RS485settime);
//    }


    /******************/

//    /****chuanglian test***/
//    automaticXml->timego++;
//   if(automaticXml->timego>=30)
//    {
//       if(automaticXml->getTestStata()==false)
//        {
//        automaticXml->setTestStata(true);
//        ControlPointFunc *pointControlFunc = new ControlPointFunc();
//       ControlPointStruct sourcePoint;
//        sourcePoint.setAddress(0x01);
//        sourcePoint.setValue(0x00);
//       QList<ControlPointStruct> sourcePointList;
//        sourcePointList.append(sourcePoint);
//        pointControlFunc->setSourceDevice("PointDevice");
//        pointControlFunc->setSourcePointList(sourcePointList);
//        QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
//        emit transferFuncSignal(sharedPointControlFunc);
//        }else
//       {
//            automaticXml->setTestStata(false);
//            ControlPointFunc *pointControlFunc = new ControlPointFunc();
//            ControlPointStruct sourcePoint;
//           sourcePoint.setAddress(0x01);
//            sourcePoint.setValue(0x01);
//            QList<ControlPointStruct> sourcePointList;
//           sourcePointList.append(sourcePoint);
//            pointControlFunc->setSourceDevice("PointDevice");
//           pointControlFunc->setSourcePointList(sourcePointList);
//            QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
//            emit transferFuncSignal(sharedPointControlFunc);
//        }
//      automaticXml->timego=0;
//    }
    /***********/


}

void LogicController::downloadFinisedSlot(PortStruct source, bool isSucceed, quint8 fileType, QString path)
{
    QFile file(path);
    QFileInfo fileinfo(path);
    QString filestr=fileinfo.suffix();
    QString filename=fileinfo.fileName();
    DownloadFileResultFunc *downloadFileResultFunc = new DownloadFileResultFunc();
    QSharedPointer<DownloadFileResultFunc> shareDownloadFileResultFunc(downloadFileResultFunc);
    downloadFileResultFunc->setTarget(source);

    if(!isSucceed)
    {
        file.remove();
        downloadFileResultFunc->setResult(DownloadFailed);
        emit transferFuncSignal(shareDownloadFileResultFunc);
    }
    else
    {
        downloadFileResultFunc->setResult(DownloadSucceed);
        emit transferFuncSignal(shareDownloadFileResultFunc);
        switch(fileType)
        {
            case PointFile:
                 {
                      System *system = System::getInstance();
                      QString appDirPath = system->appDirPath();
                      file.copy(path,appDirPath+("/Ini/Point.ini"));
                 }
            break;

            case UpdateFile:
                 {
                      System *system = System::getInstance();
                      QByteArray zipPath = path.toLatin1();
                      QByteArray appDirPath = system->appDirPath().toLatin1();
                      #ifdef Q_OS_LINUX
                      QByteArray appName    = "GateWay";
                      #endif
                      #ifdef Q_OS_WIN
                      QByteArray appName    = "GateWay.exe";
                      #endif
                      int isExist = isFileExist(zipPath.data(),appName.data());
                      if(isExist == 0)
                      {
                          QFile appFile(system->appFilePath());
                          appFile.remove();
                      }
                      miniunz(zipPath.data(),NULL,appDirPath.data());
                      file.remove();

                      QEventLoop loop;//定义一个新的事件循环
                      QTimer::singleShot(3000, &loop, SLOT(quit()));//创建单次定时器，槽函数为事件循环的退出函数
                      loop.exec();
                      system->rebootSystem();
                 }
            break;
        case OtherFile:
                    {
                    System *system = System::getInstance();
                    QString appDirPath = system->appDirPath();
                    if(filestr=="xml")
                    {
                        qDebug()<<"filenname=="<<filename;
                        if(filename=="MAC.xml")
                        {
                            QFile moveFile(("/root/")+filename);
                            moveFile.remove();
                            file.copy(path,("/root/")+filename);
                            qDebug()<<"path="<<("/root/")+filename;
                            qDebug()<<"copy MAC succery";
                            sleep(5);
                            file.remove();
                        }else
                        {
                            QFile moveFile(appDirPath+("/Xml/")+filename);
                            moveFile.remove();
                            file.copy(path,appDirPath+("/Xml/")+filename);
                            qDebug()<<"path="<<appDirPath+("/Xml/")+filename;
                            qDebug()<<"copy succery";
                            sleep(5);
                            file.remove();
                        }
                    }
                    else if(filename=="GateWay")
                    {
                        QFile moveFile(appDirPath+filename);
                        moveFile.remove();
                        file.copy(path,appDirPath+filename);
                        qDebug()<<"path="<<appDirPath+filename;
                        qDebug()<<"copy succery";
                    }

                    }
                    break;
        }
    }

    QObject *object = (QObject*)sender();
    object->disconnect();
    object->deleteLater();
}

quint16 LogicController::calculationData(const quint16 choiceData,quint16 data)
{
    switch(choiceData)
    {
    case 0: {return data;}
    case 1:{data=data/10;return data;}
    }
    return 0;
}

void LogicController::LogicCloudDataFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{
    emit transferFuncSignal(sharedFunc);
}

void LogicController::TextRecord(QString data)
{
    static QMutex mutex;
//    mutex.lock();
//    QString text;
//    QString currentTime = QDateTime::currentDateTime().toString("[MM-dd hh:mm:ss]");
//    text = currentTime + data + "\r\n";
//    QByteArray textArray = text.toLatin1();
//    fprintf(stderr, textArray.constData());

//    QFile file(QCoreApplication::applicationDirPath() + "/AutoRecord.txt");
//    file.open(QIODevice::WriteOnly | QIODevice::Append);
//    QTextStream textStream(&file);
//    textStream << text;
//    file.flush();
//    file.close();

//    mutex.unlock();
}
